package marble.model {

	import flash.display.Bitmap;
	import flash.display.SimpleButton;
	import flash.events.MouseEvent;
	
	import marble.Facade;
	
	import mx.controls.Alert;
	import mx.core.IToolTip;
	import mx.managers.ToolTipManager;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class PlanAddRemButton extends SimpleButton {

		protected var elem:Element;

		[Embed(source="/assets/addtoplan.png")]
		private var PlanAdd:Class;

		[Embed(source="/assets/addtoplan_dis.png")]
		private var PlanAddDis:Class;

		[Embed(source="/assets/deletefromplan.png")]
		private var PlanDel:Class;

		[Embed(source="/assets/deletefromplan_dis.png")]
		private var PlanDelDis:Class;
				
		protected var facade:Facade = Facade.getInstance();
		private var toolTip:IToolTip;
		
		private var tipAdd:String = facade.locale.translate('Add to plan');
		private var tipRem:String = facade.locale.translate('Delete from plan');
		protected var error:String = facade.locale.translate('Operation could not be executed');

		// prevent from calling remote method multiple times
		protected var block:Boolean = false;

		public function PlanAddRemButton(elem:Element) {

			this.elem = elem;
			setIcons();

			addEventListener(MouseEvent.ROLL_OVER, onMouseOver);
			addEventListener(MouseEvent.ROLL_OUT, onMouseLeave);
			addEventListener(MouseEvent.CLICK, onMouseClick);
		}

		private function onMouseOver(event:MouseEvent):void {
			showToolTip();
		}

		private function onMouseLeave(event:MouseEvent):void {
			hideToolTip();
		}

		protected function onMouseClick(event:MouseEvent):void {
			if (!block) {
				block = true;
				var fun:String = elem.is_plan ? "deletePlanElement" : "addPlanElement";
				facade.callRemote(fun, [elem.id],
					function (event:ResultEvent):void {
						if (event.result == true) {
							elem.is_plan = !elem.is_plan;
							(parent as Plan).redraw();
							setIcons();
						} else {
							Alert.show(error + "!", "Alert");
						}
						block = false;
						hideToolTip();
					},
					function (event:FaultEvent):void {
						block = false;
						hideToolTip();
					}
				);
			}
		}

		protected function showToolTip():void {
			if (toolTip == null) {
				toolTip = ToolTipManager.createToolTip(
					isActive() ? tipRem : tipAdd,
					x, y
				);
			}
		}

		protected function hideToolTip():void {
			if (toolTip) {
				ToolTipManager.destroyToolTip(toolTip);
				toolTip = null;
			}
		}

		protected function setIcons():void {

			var add:Bitmap = new PlanAdd();
			var add_dis:Bitmap = new PlanAddDis();

			var rem:Bitmap = new PlanDel();
			var rem_dis:Bitmap = new PlanDelDis();

			upState = isActive() ? rem_dis : add_dis;
			overState = downState = hitTestState = isActive() ? rem : add;
		}
		
		protected function isActive():Boolean {
			return elem.is_plan;
		}
	}
}